package binding

import (
	"context"
	"encoding/json"
	"group-card/common/kelas"
	"group-card/common/response"
	"group-card/common/tool"
	"group-card/rpc/card/cardclient"

	"group-card/api/internal/svc"
	"group-card/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type BindingListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewBindingListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindingListLogic {
	return &BindingListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BindingListLogic) BindingList(req *types.ListBindingRequest) (resp *types.ListBindingResponse, err error) {
	data, err := l.svcCtx.Card.BindingList(l.ctx, &cardclient.BindingListRequest{
		PageNum:    req.PageNum,
		PageSize:   req.PageSize,
		UserId:     req.UserId,
		CardNumber: req.CardNumber,
		FaceValue:  req.FaceValue,
		Status:     req.Status,
	})

	if err != nil {
		reqStr, _ := json.Marshal(req)
		logx.WithContext(l.ctx).Errorf("获取卡片绑定列表失败,参数:%s,异常:%s", reqStr, err.Error())
		return &types.ListBindingResponse{Code: response.ErrCode, Message: "获取卡片绑定列表失败"}, nil
	}

	for _, value := range data.List {
		kls := new(kelas.Kelas)
		user, err := kls.GetUser(value.UserId)
		if err == nil {
			tool.GLogLine(user.Data.Name, err)
		}

		org, err := kls.GetOrg(value.Id)
		if err == nil {
			tool.GLogLine(org.Data.Name, err)
		}

	}

	return &types.ListBindingResponse{
		Code:     response.SuccessCode,
		Message:  "获取卡片绑定列表成功",
		PageNum:  req.PageNum,
		Data:     data.List,
		PageSize: req.PageSize,
		Success:  true,
		Total:    data.Total,
	}, nil
}
